import './Workbench.less'
import { useCharts } from '@/hooks/useCharts'
import { useEffect, useRef, useState } from 'react'
import { formatMoney } from '@/utils/utils'
import { useCountUp } from 'react-countup'
import { useModel, history } from '@umijs/max'
import { App, Col, Row, Skeleton } from 'antd'
import HomeCard from '@/components/HomeCard'
import PanelBoxItem from '@/components/PanelBoxItem'
import CheckCustomerService from '@/components/CheckCustomerService'

const Workbench = () => {
  const { message, modal } = App.useApp()
  const { userInfo, userAllInfo, platformType } = useModel('Global')

  const { GetOrderDataCount, GetCommonFunctionMenu, GetRiskBillList, GetWithdrawalCount } = useModel('Workbench')

  const [riskPieRef, riskPieChart, riskLoading, setRiskLoading] = useCharts() // 风控饼图

  const [withdrawalPieRef, withdrawalPieChart, withdrawalLoading, setWithdrawaLoading] = useCharts() // 提现饼图

  const withdrawalCountRef = useRef(null)
  const withdrawalCount = useCountUp({
    ref: withdrawalCountRef,
    start: 0,
    end: 0,
    duration: 3,
    suffix: '元',
    decimals: 2
  })

  const [panelData, setPanelData] = useState([]) // 面板数据
  const [panelLoading, setPanelLoading] = useState(true) // 面板loading

  const [commonFunctionData, setCommonFunctionData] = useState([]) // 常用功能数据
  const [commonFunctionLoading, setCommonFunctionLoading] = useState(true) // 常用功能loading

  useEffect(() => {
    getOrderData()
    getCommonFunctionData()

    // 判断七牛云是否交费
    if (!userAllInfo?.qiNiu_is_deduction && platformType === 0) {
      modal.confirm({
        title: '充值提示',
        content: '当前七牛云（图片云存储服务）费用余额已不足，未避免正常使用（过期将无法正常显示图片内容）请前往充值',
        okText: '去充值',
        cancelText: '关闭',
        markCancel: false,
        onOk: () => {
          history.push('/riskRecharge')
        }
      })
    }
  }, [])

  // 获取订单数据
  const getOrderData = async () => {
    setPanelLoading(true)
    let res = await GetOrderDataCount()
    if (res) {
      setPanelData(res)
      setPanelLoading(false)
    }
  }

  // 获取常用功能数据
  const getCommonFunctionData = async () => {
    setCommonFunctionLoading(true)
    let res = await GetCommonFunctionMenu()
    if (res) {
      setCommonFunctionData(res)
      setCommonFunctionLoading(false)
    }
  }

  // 常用功能点击
  const handleCommonFnClick = item => {
    if (item.is_auth) {
      history.push(item.link)
    } else {
      message.error('您暂无查看该内容的权限!')
    }
  }

  useEffect(() => {
    if (riskPieChart) getRiskData()
  }, [riskPieChart])

  useEffect(() => {
    if (withdrawalPieChart) getWithdrawalData()
  }, [withdrawalPieChart])

  // 获取风控数据
  const getRiskData = async () => {
    setRiskLoading(true)
    const res = await GetRiskBillList()
    if (res) {
      let { balance, expense_amount } = res
      const data = [
        { value: expense_amount, name: '已消耗' },
        { value: balance, name: '剩余' }
      ]
      const total = data.reduce((prev, cur) => {
        return Number(prev) + Number(cur.value)
      }, 0)
      riskPieChart?.setOption({
        tooltip: {
          trigger: 'item',
          backgroundColor: '#1E1B39',
          borderRadius: 10,
          borderColor: '#1E1B39',
          formatter: values => {
            return `
          <div style='text-align: center'>
             <div style='color: #E5E5EF;font-size: 16px;font-weight: 400'>${values.data.name}</div>
             <div style='color:#fff;font-size: 18px;font-weight: 700;'>${formatMoney(values.data.value, true)}</div>
          <div>`
          }
        },
        legend: {
          bottom: '0%',
          left: 'center',
          itemWidth: 15,
          itemHeight: 15,
          itemGap: 40,
          icon: 'circle',
          // selectedMode: false,
          textStyle: {
            color: '#9291A5',
            fontSize: 16
          },
          formatter: name => {
            const target = data.find(item => item.name === name)
            if (target.value === 0 && total === 0) return `${name} 0%`
            const percent = ((target.value / total) * 100).toFixed(1)
            return `${name} ${percent}%`
          }
        },
        color: ['#a8b9f6', '#4A3AFF'],
        graphic: [
          {
            type: 'text',
            left: 'center',
            top: '45%',
            style: {
              text: '当前风控余额',
              textAlign: 'center',
              fill: '#615E83',
              fontSize: 16,
              fontWeight: 400
            }
          },
          {
            type: 'text',
            left: 'center',
            top: '52%',
            style: {
              text: formatMoney(balance, true),
              textAlign: 'center',
              fill: '#333',
              fontSize: 30,
              fontWeight: 600
            }
          }
        ],
        series: [
          {
            // silent: true,
            type: 'pie',
            radius: ['70%', '80%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 20,
              borderColor: '#fff',
              borderWidth: 5
            },
            label: {
              show: false
            },
            data
          }
        ]
      })
      setRiskLoading(false)
    }
  }

  // 获取提现数据
  const getWithdrawalData = async () => {
    setWithdrawaLoading(true)
    const res = await GetWithdrawalCount()
    if (res) {
      let { un_drawn_sum, withdrawal_sum, withdrawal_success, withdrawal_freeze } = res
      const data = [
        { value: un_drawn_sum, name: '未提现总和' },
        { value: withdrawal_freeze, name: '提现冻结' },
        { value: withdrawal_success, name: '已提现总和' }
      ]
      withdrawalCount.update(withdrawal_sum)
      withdrawalPieChart?.setOption({
        tooltip: {
          trigger: 'item',
          backgroundColor: '#1E1B39',
          borderRadius: 10,
          borderColor: '#1E1B39',
          formatter: values => {
            return `
          <div style='text-align: center'>
             <div style='color: #E5E5EF;font-size: 16px;font-weight: 400'>${values.data.name}</div>
             <div style='color:#fff;font-size: 18px;font-weight: 700;'>${formatMoney(values.data.value, true)}</div>
          <div>`
          }
        },
        color: ['#4A3AFF', '#93AAFD', '#C6D2FD'],
        series: [
          {
            type: 'pie',
            radius: '80%',
            label: {
              show: false
            },
            data
          }
        ]
      })
      setWithdrawaLoading(false)
    }
  }

  return (
    <div className='workbench'>
      <CheckCustomerService />
      <HomeCard
        width={'100%'}
        margin={[0, 0, 20, 0]}
        leftContent={{
          title: '👏 欢迎回来，' + userInfo?.real_name
        }}
      >
        <div className='panel_content'>
          <Row>
            {panelLoading
              ? new Array(8).fill(0).map((item, index) => {
                  return (
                    <Col xs={12} sm={12} md={8} lg={8} xl={6} key={Math.random() * 100}>
                      <div
                        style={{
                          padding: '20px 40px',
                          boxSizing: 'border-box'
                        }}
                      >
                        <Skeleton active avatar />
                      </div>
                    </Col>
                  )
                })
              : panelData.map((item, index) => {
                  return (
                    <Col xs={12} sm={12} md={8} lg={8} xl={6} key={index}>
                      <PanelBoxItem item={item} />
                    </Col>
                  )
                })}
          </Row>
        </div>
      </HomeCard>

      <HomeCard
        width={'100%'}
        margin={[0, 0, 20, 0]}
        leftContent={{
          title: '常用功能'
        }}
      >
        <div className='commonly_content'>
          {commonFunctionLoading
            ? new Array(6).fill(0).map((item, index) => {
                return (
                  <div
                    style={{
                      marginTop: '20px',
                      display: 'flex',
                      flexDirection: 'column',
                      alignItems: 'center'
                    }}
                    key={Math.random() * 100}
                  >
                    <Skeleton.Avatar active shape={'square'} size={'large'} />
                    <div style={{ marginTop: '10px' }}>
                      <Skeleton.Input active size={'small'} />
                    </div>
                  </div>
                )
              })
            : commonFunctionData.map((item, index) => {
                return (
                  <div
                    key={item.name}
                    className={item.is_auth ? 'commonly_item' : 'commonly_item btn_disabled'}
                    onClick={() => handleCommonFnClick(item)}
                  >
                    <div className='commonly_item_icon' style={{ backgroundImage: `url(${item.icon_url})` }} />
                    <div className='commonly_item_content'>{item.name}</div>
                  </div>
                )
              })}
        </div>
      </HomeCard>

      <div className='chart_wrapper'>
        <HomeCard
          width={'50%'}
          height={'400px'}
          leftContent={{
            title: '风控账单',
            subTitle: '账单'
          }}
          loading={riskLoading}
        >
          <div ref={riskPieRef} className='chart_box' />
        </HomeCard>

        <HomeCard
          width={'50%'}
          height={'400px'}
          leftContent={{
            title: '提现管理',
            subTitle: '提现'
          }}
          rightContent={{
            title: <span style={{ fontFamily: 'DINPro-Medium' }} ref={withdrawalCountRef}></span>,
            subTitle: '总计'
          }}
          loading={withdrawalLoading}
        >
          <div ref={withdrawalPieRef} className='chart_box' />
        </HomeCard>
      </div>
    </div>
  )
}
export default Workbench
